//index.js
const app = getApp()
const startTime = 0
const endTime = 0
const util = require('../../lib/utils.js')

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    reload: false,
    invoices: [],
    wxacodeSrc: '',
  },

  onLoad: function () {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    this.queryData()
    wx.stopPullDownRefresh()
  },
  //下拉刷新
  onPullDownRefresh: function () {
    console.log('invoice onPullDownRefresh')
    this.onLoad()
  },

  onShow: function() {
    //每次展示页面都会调用
    if (app.globalData.reload) {
      console.log('invoice onShow')
      this.onLoad()
      app.globalData.reload = false
    }
  },

  onNewInvoiceTitle: function () {
    console.log('invoice new.')
    wx.navigateTo({
      url: '../invoiceForm/invoiceForm',
    })
  },

  invoiceDetail: function (event) {
    if (this.endTime - this.startTime >= 350) {
      console.log('long press')
      return;
    }
    console.log('invoice invoiceDetail => ', event)

    app.globalData.invoice = this.data.invoices[event.currentTarget.dataset.idx]
    console.log("invoice set globalData(invoice) => ", app.globalData.invoice)
    
    wx.navigateTo({
      url: '../invoiceForm/invoiceForm?idx=' + event.currentTarget.dataset.idx,
    })
  },

  bindTouchStart: function (e) {
    this.startTime = e.timeStamp;
  },
  bindTouchEnd: function (e) {
    this.endTime = e.timeStamp;
  },

  deleteInvoice: function(e) {
    console.log('invoice delete => ', e)
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认删除吗?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '正在删除',
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
          console.log('invoice deleteInvoice modal => ', res)
          wx.cloud.callFunction({
            name: 'invoice_delete_by_id',
            data: {
              invoiceId: that.data.invoices[e.currentTarget.dataset.idx]._id
            },
            success: res => {
              wx.hideLoading()
              console.log("invoice invoice_delete_by_id => ", res)
              that.onLoad()
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '删除失败',
              })
              console.error('[云函数] [invoice_delete_by_id] 调用失败：', err)
            }
          })
        }
      }
    })
    
  },

  onBillingSubmit: function(e) {
    console.log('invoice billing submit.')
    
    //form sumbit
    // var objData = e.detail.value
    //data-idx
    var bill = {}
    bill.invoice = this.data.invoices[e.currentTarget.dataset.idx]
    wx.scanCode({
      fail: function(res) {
        console.log("invalid qrcode => ", res)
        if (res.errMsg != 'scanCode:fail cancel') {
          wx.showToast({
            title: '无效二维码',
            //image: ''
          })
        }
      },
      success: function(res) {
        // res.charSet
        // res.result
        // res.rawData
        // res.errMsg
        // res.scanType
        console.log("invoice scanCode => ", res)
        //ivc:room/table
        var info = res.result
        if (info.indexOf('iv:') > 0) {
            bill.billName = info.split(':')[1] 
            wx.setStorage({
              key: 'bill',
              data: bill,
              success: res => {
                console.log("invoice set stroage => ", res)
              }
            })
          wx.navigateTo({
            url: '../billPreview/billPreview',
          })
        } else {
          wx.showToast({
            title: '无效二维码',
            icon: 'none'
          })
        }
      }
    })
    //表单数据
    // var objData = e.detail.value;
    // console.log("invoice onBillingSubmit => ", objData)
    // console.log("invoice data.invoices => ", this.data.invoices)

    // app.globalData.invoice = this.data.invoices[objData.idx]
    // console.log("invoice set globalData(invoice) => ", app.globalData.invoice)

    // wx.navigateTo({
    //   url: '../invoiceBilling/invoiceBilling?idx=' + objData.idx,
    // })
  },

  queryData: function() {

    wx.showLoading({
      title: '加载中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    wx.cloud.callFunction({
      name: 'invoice_query',
      data: {
      },
      success: res => {
        wx.hideLoading()
        console.log("invoice invoice_query => ", res)
        for (var index in res.result.data) {
          //console.log(new Date(res.result.data[index].createDate).toLocaleString())
          res.result.data[index].createDate = util.tsFormatTime(res.result.data[index].createDate, 'Y-M-D h:m:s')
        }
        this.setData({
          invoices: res.result.data
        })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '发票抬头加载失败',
        })
        console.error('[云函数] [invoice_query] 调用失败：', err)
      }
    })
  },

  onGetWXACode() {
    const fileID = wx.getStorageSync(this.data.invoice._id)
    if (fileID) {
      this.setData({
        wxacodeSrc: fileID
      })
      console.log(`从本地缓存中取得了小程序码的云文件 ID：${fileID}`)
    } else {
      wx.cloud.callFunction({
        name: 'openapi',
        data: {
          action: 'getWXACode',
          path: 'pages/invoiceForm/invoiceForm',
          name: this.data.invoice._id,
        },
        success: res => {
          console.warn('[云函数] [openapi] wxacode.get 调用成功：', res)
          this.setData({
            wxacodeSrc: res.result
          })
          wx.setStorageSync(this.data.invoice._id, res.result)
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '获取小程序码失败',
          })
          console.error('[云函数] [openapi] wxacode.get 调用失败：', err)
        }
      })
    }
  },

  clearWXACodeCache() {
    wx.removeStorageSync(this.invoice._id)
    this.setData({
      wxacodeSrc: '',
    })
    wx.showToast({
      title: '清除成功',
    })
  },
})